// API基础URL配置
const API_BASE_URL = 'http://localhost:5004';
// 检查并更新用户登录状态
let Essay_id;
let Version_id;
let User_id;
async function updateUserLoginStatus() {
    const userInfoDiv = document.querySelector('.user-info');
    const authButtons = document.querySelector('.auth-buttons');
    const usernameDisplay = document.getElementById('username-display');
    const userInfo = localStorage.getItem('user');
    console.log(userInfo);// 获取最新的用户信息
    const userProfile = await fetchUserProfile();

    if (userProfile) {
        userInfoDiv.style.display = 'block';
        authButtons.style.display = 'none';
        usernameDisplay.textContent = userProfile.username;
    } else {
        userInfoDiv.style.display = 'none';
        authButtons.style.display = 'block';
    }
}

window.addEventListener('DOMContentLoaded', () => {
const urlParams = new URLSearchParams(window.location.search);
const essay_id = urlParams.get('essay_id');
const version_id = urlParams.get('version_id');
Essay_id= essay_id;
Version_id=version_id;

const versionId=parseInt(version_id, 10);
const user_id = urlParams.get('user_id');
const User_id=user_id;

  console.log("接收到的数据:", { essay_id, version_id ,user_id});
  // 页面加载时调用
document.addEventListener('DOMContentLoaded', fetchRankingData(user_id,essay_id, version_id));
fetchScoreTrend(essay_id);
updateRadarChart(essay_id, version_id);
initScoreCard(essay_id, version_id, appState.currentUser.token);
});

function  getCurrentEssayId(){
return Essay_id;} //
function getCurrentVersionId(){
return Version_id;}

// 全局状态管理
const appState = {
  currentUser: {
    id: localStorage.getItem('userId') || '',
    token: localStorage.getItem('token') || ''
  },
  currentEssay: {
    id: getCurrentEssayId(),
    versions: getCurrentVersionId(),
  }
};
// 获取用户信息的函数
async function fetchUserProfile() {
    try {
        const token = localStorage.getItem('token');
        if (!token) return null;

        const response = await fetch(`${API_BASE_URL}/user/profile`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        const data = await response.json();
        if (data.code === 200) {
            return data.data;
        } else {
            console.error('获取用户信息失败:', data.message);
            return null;
        }
    } catch (error) {
        console.error('获取用户信息出错:', error);
        return null;
    }
}

// 退出登录处理函数
function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');

        const modal = document.getElementById('user-modal');
        if (modal) {
            modal.style.display = 'none';
        }

        showMessage('已成功退出登录');

        // 更新界面显示
        const userInfoDiv = document.querySelector('.user-info');
        const authButtons = document.querySelector('.auth-buttons');

        userInfoDiv.style.display = 'none';
        authButtons.style.display = 'block';

        window.location.href = 'index.html';
    }
}

// 消息提示函数
function showMessage(message) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message-toast';
    messageDiv.textContent = message;
    document.body.appendChild(messageDiv);

    setTimeout(() => messageDiv.classList.add('show'), 10);

    setTimeout(() => {
        messageDiv.classList.remove('show');
        setTimeout(() => messageDiv.remove(), 300);
    }, 3000);
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', function() {
    // 更新用户登录状态
    updateUserLoginStatus();

    // 设置用户详情模态窗口事件
    const usernameDisplay = document.getElementById('username-display');
    if (usernameDisplay) {
        usernameDisplay.onclick = async function() {
            const userProfile = await fetchUserProfile();
            if (userProfile) {
                const userModal = document.getElementById('user-modal');
                document.getElementById('modal-username').textContent = userProfile.username;
                document.getElementById('modal-email').textContent = userProfile.email;
                document.getElementById('modal-userid').textContent = userProfile.user_id;
                userModal.style.display = 'block';
            } else {
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                window.location.href = 'auth.html#login';
            }
        }
    }

    // 设置模态窗口关闭事件
    const closeButton = document.querySelector('.close-button');
    if (closeButton) {
        closeButton.onclick = function() {
            document.getElementById('user-modal').style.display = 'none';
        }
    }

    // 点击模态窗口外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('user-modal');
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    }
});
// 页面加载时调用
document.addEventListener('DOMContentLoaded', fetchEssayCount);

//累计作品数 模块显示数据
async function fetchEssayCount() {
    try {
        // 1. 获取当前用户ID
        const userProfile = await fetchUserProfile();
//        console.log('用户信息:', userProfile);
        const user_id = userProfile.user_id;
//        console.log('用户ID:', user_id);

        // 2. 调用后端API
        const response = await fetch('http://127.0.0.1:5004/analysis/sum', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json', // 添加了缺失的Content-Type
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({
                user_id: user_id  // 修正了格式和换行问题
            })
        });  // 移除了多余的括号

        // 3. 处理响应
        if (!response.ok) {
            throw new Error(`网络响应不正常，状态码: ${response.status}`);
        }

        const data = await response.json();
        console.log('API响应数据:', data);

        if (data.code === 200) {
            // 4. 更新DOM
            document.getElementById('total-count').textContent = `${data.data.essay_count} 篇`;
            document.getElementById('monthly-count').textContent = `本月已完成 ${data.data.essay_count} 篇`;
        } else {
            throw new Error(data.message || '获取数据失败');
        }
    } catch (error) {
        console.error('获取作文数量时出错:', error);
        // 5. 错误处理
        document.getElementById('total-count').textContent = '加载失败';
        document.getElementById('monthly-count').textContent = '数据错误';
    }
}

// 页面加载时初始化历史排名
document.addEventListener('DOMContentLoaded', initRankingCard);
// 获取排名数据
async function fetchRankingData(userId, essayId, versionId) {
  try {
  // 1. 获取当前用户ID
        const userProfile = await fetchUserProfile();
//        console.log('用户信息:', userProfile);
        const user_id = userProfile.user_id;
//        console.log('用户ID:', user_id);
    const response = await fetch('http://127.0.0.1:5004/analysis/rank', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({

        essay_id: essayId,
        version_id: versionId
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
   console.log(data.data);
    // 验证返回数据结构
    if (data.code !== 200 || !data.data?.percentile_rank) {
      throw new Error(data.message || '无效的排名数据');
    }

    updateRankingCard(data.data);

  } catch (error) {
    console.error('获取排名失败:', error);
    return null;
  }
}

// 更新排名卡片UI
function updateRankingCard(rankingData) {
  const percentEl = document.getElementById('ranking-percent');
  const descEl = document.getElementById('ranking-description');
//    const score = document.getElementById('score');
console.log("传入数据：",rankingData);
  if (!rankingData) {
    percentEl.innerHTML = '<span class="text-red-500">数据异常</span>';
    descEl.textContent = '排名计算失败，请重试';
    return;
  }

  const percentile = rankingData.percentile_rank;
  const topPercent = Math.round(100 - percentile);

  // 更新百分比显示
  percentEl.innerHTML = `前 ${topPercent}%`;

  // 更新描述文本
  descEl.textContent = `超过 ${Math.round(percentile)}% 的同学`;

  // 根据排名添加动态效果
  if (topPercent <= 10) {
    percentEl.classList.add('text-purple-600');
    percentEl.classList.remove('text-yellow-500', 'text-gray-500');
    descEl.innerHTML += ' <i class="fas fa-trophy text-yellow-400"></i>';
  } else if (topPercent <= 30) {
    percentEl.classList.add('text-yellow-500');
    percentEl.classList.remove('text-purple-600', 'text-gray-500');
  } else {
    percentEl.classList.add('text-gray-500');
    percentEl.classList.remove('text-purple-600', 'text-yellow-500');
  }
}

// 初始化排名卡片
async function initRankingCard() {
  // 从当前页面或全局状态获取作文信息
  const userId = localStorage.getItem('user_id');
  const essayId = getCurrentEssayId(); // 需要你实现这个函数
  const versionId = getCurrentVersionId(); // 需要你实现这个函数

  if (!userId || !essayId || !versionId) {
    updateRankingCard(null);
    return;
  }

  // 获取数据并更新UI
  const rankingData = await fetchRankingData(userId, essayId, versionId);
  updateRankingCard(rankingData);

  // 可选：添加自动刷新（每5分钟）
  setInterval(async () => {
    const newData = await fetchRankingData(userId, essayId, versionId);
    updateRankingCard(newData);
  }, 5 * 60 * 1000);
}

// 页面加载初始化
document.addEventListener('DOMContentLoaded', initRadarChart);

/**
 * 初始化雷达图（适配图片中的样式）
 */
function initRadarChart() {
    const chartDom = document.getElementById('radarChart');
    if (!chartDom) return;

    // 初始化图表实例
    radarChart = echarts.init(chartDom);

    // 默认配置（保持与图片一致的风格）
    const defaultOption = {
        title: {
            text: "评分维度分析",
            left: "center",
            textStyle: {
                fontSize: 18,
                fontWeight: "bold",
                color: "#333"
            }
        },
        tooltip: {
            trigger: "item",
            formatter: params => {
                return `${params.name}<br/>得分: ${params.value}`;
            }
        },
        radar: {
            shape: 'circle',
            indicator: [
                { name: "词评分", max: 25, color: '#1890FF' },
                { name: "句子评分", max: 25, color: '#722ED1' },
                { name: "结构评分", max: 25, color: '#13C2C2' },
                { name: "内容评分", max: 25, color: '#F759AB' }
            ],
            radius: "65%",
            axisName: {
                color: "#666",
                fontSize: 12,
                fontWeight: "bold"
            },
            splitLine: {
                lineStyle: {
                    color: "rgba(0, 0, 0, 0.1)",
                    width: 1
                }
            },
            splitArea: {
                show: true,
                areaStyle: {
                    color: ["rgba(25, 180, 120, 0.1)", "rgba(25, 180, 120, 0.05)"]
                }
            },
            axisLine: {
                lineStyle: {
                    color: "rgba(0, 0, 0, 0.3)",
                    width: 1
                }
            }
        },
        series: [{
            type: "radar",
            lineStyle: {
                width: 2,
                color: "rgba(54, 162, 235, 0.8)"
            },
            symbol: "circle",
            symbolSize: 6,
            itemStyle: {
                color: "#fff",
                borderColor: "rgba(54, 162, 235, 1)",
                borderWidth: 2
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(58, 77, 233, 0.5)' },
                    { offset: 1, color: 'rgba(0, 195, 255, 0.2)' }
                ])
            },
            data: [{
                value: [18, 16, 20, 15], // 初始零值
                name: "上次数据"
            }]
        }]
    };

    radarChart.setOption(defaultOption);

    // 响应式调整
    window.addEventListener('resize', function() {
        radarChart && radarChart.resize();
    });
    // 在initRadarChart中添加容器检查
const chartDom1 = document.getElementById('scoreChart');
if (!chartDom1) {
  console.error('错误: 找不到DOM容器 #scoreChart');
  // 创建备用容器（应急方案）
  const fallbackContainer = document.createElement('div');
  fallbackContainer.id = 'scoreChart';
  document.body.appendChild(fallbackContainer);
};
}

/**
 * 更新雷达图数据（增强错误处理）
 */
async function updateRadarChart(essayId, versionId) {
    if (!radarChart) initRadarChart();

    try {
        // 显示加载状态
        radarChart.showLoading();


        // 获取数据
        const response = await fetch('http://127.0.0.1:5004/visualization/radar', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({ essay_id: essayId, version_id: versionId })
        });

        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        const result = await response.json();
        console.log('接口返回数据:', JSON.stringify(result));
        console.log('接口返回数据:', JSON.stringify(result.data));
        if (result.code !== 200) throw new Error(result.message || 'Invalid data');

        // 验证数据格式
        const validateScores = (scores) => {
            if (!Array.isArray(scores) || scores.length !== 4) {
                throw new Error('数据格式错误：需要4个评分维度');
            }
            return scores.map(v => Math.min(Math.max(v, 0), 25)); // 限制在0-25范围
        };

        const scores = validateScores(result.data.values || []);
        console.log(scores);
        // 在setOption之前添加
console.log('最终渲染数据:', {
    scores: scores,
    dimensions: ["词评分","句子评分","结构评分","内容评分"],
    containerSize: document.getElementById('scoreChart').getBoundingClientRect()
});
// 完整图表配置（匹配图片样式）
        radarChart.setOption({
        title: {
            text: "评分维度分析",
            left: "center",
            textStyle: {
                fontSize: 18,
                fontWeight: "bold",
                color: "#333"
            }
        },
         tooltip: {
            trigger: "item",
            formatter: params => {
                return `${params.name}<br/>得分: ${params.value}`;
            }
        },
            radar: {
                indicator: [
                    { name: "词评分", max: 25, color: '#1890FF' },
                    { name: "句子评分", max: 25, color: '#722ED1' },
                    { name: "结构评分", max: 25, color: '#13C2C2' },
                    { name: "内容评分", max: 25, color: '#F759AB' }
                ],
                 axisLabel: {
            show: true,
            formatter: (name, index) => {
                return `${name}: ${scores[index]}`; // 显示"维度: 分数"
            },
            color: '#333'}

    },
    radar: {
            shape: 'circle',
            indicator: [
                { name: "词评分", max: 25, color: '#1890FF' },
                { name: "句子评分", max: 25, color: '#722ED1' },
                { name: "结构评分", max: 25, color: '#13C2C2' },
                { name: "内容评分", max: 25, color: '#F759AB' }
            ],
            radius: "65%",
            axisName: {
                color: "#666",
                fontSize: 12,
                fontWeight: "bold"
            },
            splitLine: {
                lineStyle: {
                    color: "rgba(0, 0, 0, 0.1)",
                    width: 1
                }
            },
            splitArea: {
                show: true,
                areaStyle: {
                    color: ["rgba(25, 180, 120, 0.1)", "rgba(25, 180, 120, 0.05)"]
                }
            },
            axisLine: {
                lineStyle: {
                    color: "rgba(0, 0, 0, 0.3)",
                    width: 1
                }
            }
        },
        series: [{
            type: "radar",
            lineStyle: {
                width: 2,
                color: "rgba(54, 162, 235, 0.8)"
            },
            symbol: "circle",
            symbolSize: 6,
            itemStyle: {
                color: "#fff",
                borderColor: "rgba(54, 162, 235, 1)",
                borderWidth: 2
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(58, 77, 233, 0.5)' },
                    { offset: 1, color: 'rgba(0, 195, 255, 0.2)' }
                ])
            },
            data: [{
                value: scores, // 初始零值
                name: "本次评分数据"
            }]
        }]

        }, true);

    } catch (error) {
        console.error('雷达图更新失败:', error);

        // 错误状态显示（红色警示）
        radarChart.setOption({
            series: [{
                data: [{
                    value: [0, 0, 0, 0],
                    name: '加载失败',
                    itemStyle: { color: '#ff4d4f' }
                }]
            }],
            title: {
                subtext: error.message,
                subtextStyle: {
                    color: '#f56c6c',
                    fontWeight: 'bold'
                }
            }
        }, true);

//        // 3秒后自动重试
//        setTimeout(() => updateRadarChart(essayId, versionId), 3000);
    } finally {
        radarChart.hideLoading();
    }
};



// 页面加载时初始化分数趋势图
document.addEventListener('DOMContentLoaded', initScoreChart);
/**
 * 初始化分数趋势图
 */
function initScoreChart() {
  // 1. 获取DOM容器
  const chartDom = document.getElementById('scoreChart');

  // 2. 初始化ECharts实例
  scoreChart = echarts.init(chartDom);

  // 3. 设置加载中的默认配置
  scoreChart.showLoading('default', {
    text: '数据加载中...',
    color: '#3B82F6',
    textColor: '#333',
    maskColor: 'rgba(255, 255, 255, 0.8)'
  });
}

/**
 * 获取评分趋势数据
 */
async function fetchScoreTrend(essay_id) {
  try {

    // 3. 发送请求到趋势分析接口
    const response = await fetch('http://127.0.0.1:5004/visualization/trend', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({ essay_id:essay_id })
    });

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }

    const result = await response.json();
    console.log("123 ",result);
    // 4. 验证返回数据
    if (result.code !== 200 || !result.data) {
      throw new Error(result.message || '无效的趋势数据');
    }
// 初始化 scoreChart
    const scoreChart = echarts.init(document.getElementById('scoreChart'));
    scoreChart.showLoading();
  console.log(result.data.versions);
    renderScoreTrend(result.data.versions, scoreChart);


  } catch (error) {
    console.error('获取趋势数据失败:', error);
    throw error;
  }
}

/**
 * 渲染分数趋势图
 */
async function renderScoreTrend(result,scoreChart) {

  try {
    // 1. 获取趋势数据
// 1. 数据预处理
    const trendData = {
      timestamp: result.map(v => v.timestamp),
      overall_score: result.map(v => v.overall_score)
    };

    console.log('处理后的趋势数据:', trendData);

// 2. 准备图表配置
    const option = {
      animation: true,
      tooltip: {
        trigger: 'axis',
        formatter: params => {
          const date = params[0].axisValue;
          const score = params[0].data;
          return `日期: ${date.split(' ')[0]}<br/>分数: ${score}分`;
        }
      },
      xAxis: {
        type: 'category',
        data: trendData.timestamp,
        axisLabel: {
          formatter: value => {
            // 简写日期显示（如 "04-02"）
            return value.split(' ')[0].split('-').slice(1).join('-');
          }
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}分'
        },
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      series: [{
        name: '作文分数',
        data: trendData.overall_score,
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          color: '#3B82F6',
          width: 3
        },
        itemStyle: {
          color: '#3B82F6'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(59,130,246,0.2)'
            }, {
              offset: 1,
              color: 'rgba(59,130,246,0)'
            }]
          }
        },
        markPoint: {
          data: [
            { type: 'max', name: '最高分' },
            { type: 'min', name: '最低分' }
          ]
        }
      }]
    };

    // 3. 隐藏加载动画并渲染图表
    scoreChart.hideLoading();
    scoreChart.setOption(option);

    // 4. 窗口大小变化时重绘图表
    window.addEventListener('resize', function() {
      scoreChart.resize();
    });

  } catch (error) {
    console.error('渲染趋势图失败:', error);

    // 显示错误状态
    scoreChart.hideLoading();
    scoreChart.setOption({
      title: {
        text: '数据加载失败',
        subtext: error.message || '请刷新重试',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#ef4444'
        }
      }
    });
  }
}



// 初始化弹窗功能
document.addEventListener('DOMContentLoaded', function() {
  const modal = document.getElementById('score-detail-modal');
  const scoreCard = document.querySelector('.score-card-trigger'); // 注意这里的点号 给原分数卡片添加这个class

  if (!scoreCard || !modal) {
    console.error('关键元素未找到');
    return;
  }
try{

//    /​**​
// * 初始化分数卡片
// * @param {string} essayId - 文章ID
// * @param {string} versionId - 版本ID
// * @param {string} token - 用户token
// */

 // 点击分数卡片触发
  scoreCard.addEventListener('click', async function() {
  const modal = document.getElementById('score-detail-modal');
  const scoreCard = document.querySelector('.score-card-trigger');

 if (!appState.currentUser.token) {
      alert('请先登录');
      return;
    }

    modal.classList.remove('hidden');
    document.body.classList.add('overflow-hidden'); // 更标准的禁止滚动方式

    try {
    const currentVersion = String(Version_id);
    const previousVersion = Math.max(0, Version_id - 1);
     // 1. 分别获取两个接口的数据（并行请求）
    const [progressData, compareData] = await Promise.all([
      fetchUserProgress(appState.currentUser.token),
      fetchEssayComparison(Essay_id, currentVersion, appState.currentUser.token)
    ]);

    // 2. 分别存储两个接口的返回数据
    const storedData = {
      progressData: progressData,  // 存储进步分析数据
      compareData: compareData     // 存储对比分析数据
    };

    // 3. 打印存储的数据（调试用）
    console.log('存储的进步分析数据:', storedData.progressData);
    console.log('存储的对比分析数据:', storedData.compareData);


      // 渲染对比页面
      renderComparisonPage(compareData);

//
    } catch (error) {
      console.error('加载失败:', error);
      showErrorModal(modal, error);
    }
  });
}catch (error) {
      console.error('加载失败:', error);
      showErrorModal(modal, error);
    }

     // 关闭弹窗
  document.getElementById('close-modal').addEventListener('click', () => {
    modal.classList.add('hidden');
    document.body.classList.remove('overflow-hidden');
  });
  });



async function initScoreCard (essayId, versionId, token)  {
  try {
    // 显示加载状态
    const currentScoreElement = document.getElementById('current-score');
    const diffElement = document.getElementById('score-diff');

    if (!currentScoreElement || !diffElement) {
      throw new Error('分数卡片DOM元素未找到');
    }

    currentScoreElement.innerHTML = `
      <i class="fas fa-spinner fa-spin text-blue-500"></i>
    `;

    // 调试日志
    console.log('初始化参数:', { essayId, versionId });

    // 获取数据
    const [progressData, compareData] = await Promise.all([
      fetchUserProgress(token),
      fetchEssayComparison(essayId, versionId, token)
    ]);

    // 存储数据
    const storedData = { progressData, compareData };
    console.log('获取的数据:', storedData);

    // 渲染卡片
    renderScoreCard(compareData);

  } catch (error) {
    console.error('分数卡片初始化失败:', error);

    const errorElement = document.getElementById('score-diff') ||
                        document.querySelector('.score-card-trigger');

    if (errorElement) {
      errorElement.innerHTML = `
        <div class="text-red-500 text-sm">
          <i class="fas fa-exclamation-circle mr-1"></i>
          加载失败: ${error.message || '未知错误'}
        </div>
      `;
    }
  }
};

///​**​
// * 渲染分数卡片
// * @param {object} compareData - 对比数据
// */
function renderScoreCard  (compareData)  {
  if (!compareData) {
    throw new Error('比较数据不能为空');
  }

  // 解构数据
  const {
    essay_1: previousEssay,
    essay_2: currentEssay,
    score_comparison: scoreDiff
  } = compareData;

  // 获取分数
  const currentScore = currentEssay?.overall_score ?? 0;
  const previousScore = previousEssay?.overall_score ?? 0;
  const diff = scoreDiff?.overall_score_diff ?? 0;
  const isImproved = diff >= 0;

  // 更新DOM
  updateScoreDisplay(currentScore, previousScore, diff, isImproved);
};

///​**​
// * 更新分数显示
// */
function updateScoreDisplay  (currentScore, previousScore, diff, isImproved)  {
  const currentScoreElement = document.getElementById('current-score');
  const diffElement = document.getElementById('score-diff');
  const scoreCard = document.querySelector('.score-card-trigger');

  if (!currentScoreElement || !diffElement || !scoreCard) return;

  // 更新分数
  currentScoreElement.textContent = `${currentScore}分`;

  // 更新差值
  diffElement.innerHTML = `
    <i class="fas ${isImproved ? 'fa-arrow-up text-green-500' : 'fa-arrow-down text-red-500'}"></i>
    <span class="${isImproved ? 'text-green-500' : 'text-red-500'}">
      较上次${isImproved ? '提升' : '下降'} ${Math.abs(diff)}分
    </span>
  `;

  // 设置悬停提示
  scoreCard.dataset.currentScore = currentScore;
  scoreCard.dataset.previousScore = previousScore;
  scoreCard.dataset.diff = diff;
  scoreCard.title = `当前: ${currentScore}分 | 上次: ${previousScore}分\n点击查看详细分析`;
};


// 渲染对比页面
function renderComparisonPage(compareData) {
  // 设置作文元信息
  document.getElementById('essay-meta').innerHTML = `
    <span>作文ID: ${Essay_id || 'N/A'}</span> |

  `;

  // 渲染总分对比
  renderTotalScoreComparison(
    compareData.essay_1.overall_score,
    compareData.essay_2.overall_score,
    compareData.score_comparison.overall_score_diff
  );

  // 渲染四维度卡片
  renderDimensionCards([
    {
      name: '词汇',
      icon: 'fa-book',
      v1: compareData.essay_1.vocabulary_score,
      v2: compareData.essay_2.vocabulary_score,
      diff: compareData.score_comparison.vocabulary_diff,
      analysis: compareData.analysis_report.find(r => r.includes('词汇')) || ''
    },
    {
      name: '句子',
      icon: 'fa-align-left',
      v1: compareData.essay_1.sentence_score,
      v2: compareData.essay_2.sentence_score,
      diff: compareData.score_comparison.sentence_diff,
      analysis: compareData.analysis_report.find(r => r.includes('句子')) || ''
    },
    {
      name: '结构',
      icon: 'fa-project-diagram',
      v1: compareData.essay_1.structure_score,
      v2: compareData.essay_2.structure_score,
      diff: compareData.score_comparison.structure_diff,
      analysis: compareData.analysis_report.find(r => r.includes('结构')) || ''
    },
    {
      name: '内容',
      icon: 'fa-file-text',
      v1: compareData.essay_1.content_score,
      v2: compareData.essay_2.content_score,
      diff: compareData.score_comparison.content_diff,
      analysis: compareData.analysis_report.find(r => r.includes('内容')) || ''
    }
  ]);

  // 渲染雷达图
  renderRadarChart({
    labels: ['词汇', '句子', '结构', '内容'],
    v1Data: [
      compareData.essay_1.vocabulary_score,
      compareData.essay_1.sentence_score,
      compareData.essay_1.structure_score,
      compareData.essay_1.content_score
    ],
    v2Data: [
      compareData.essay_2.vocabulary_score,
      compareData.essay_2.sentence_score,
      compareData.essay_2.structure_score,
      compareData.essay_2.content_score
    ]
  });

  // 渲染改进建议
  renderImprovementSuggestions(compareData.analysis_report);
}

function renderTotalScoreComparison(score1, score2, diff) {
  const el = document.getElementById('total-score-comparison');
  if (!el) return;

  el.innerHTML = `
    <div class="flex items-center justify-between w-full">
      <!-- 当前版本 -->
      <div class="text-center flex-1">
        <div class="text-sm text-gray-500 mb-1">前一版本</div>
        <div class="text-4xl font-bold text-gray-500">${score1}</div>
      </div>

      <!-- 对比中心 -->
      <div class="flex flex-col items-center mx-4">
        <div class="flex items-center ${diff >= 0 ? 'text-green-600' : 'text-red-600'}">
          ${diff >= 0 ? `
            <i class="fas fa-arrow-up mr-1"></i>
            <span>+${diff}分</span>
          ` : `
            <i class="fas fa-arrow-down mr-1"></i>
            <span>${diff}分</span>
          `}
        </div>
        <div class="text-gray-400 text-xs mt-1">较上一版本</div>
      </div>

      <!-- 前一版本 -->
      <div class="text-center flex-1">
        <div class="text-sm text-gray-500 mb-1">当前版本</div>
        <div class="text-4xl font-bold text-blue-600">${score2}</div>
      </div>
    </div>
  `;
}
// 渲染维度卡片
function renderDimensionCards(dimensions) {
  const container = document.getElementById('dimension-cards');
  if (!container) return;

  container.innerHTML = dimensions.map(dim => `
    <div class="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
      <div class="flex items-center mb-3">
        <div class="w-10 h-10 rounded-full bg-${getDimensionColor(dim.name)}-100 flex items-center justify-center mr-3">
          <i class="fas ${dim.icon} text-${getDimensionColor(dim.name)}-600"></i>
        </div>
        <h4 class="font-medium">${dim.name}</h4>
      </div>

      <div class="flex items-center justify-between">
        <span class="text-gray-500">前一版本</span>
        <span class="font-bold">${dim.v1}</span>
      </div>
      <div class="h-2 bg-gray-100 rounded-full my-2 overflow-hidden">
        <div class="h-full bg-${getDimensionColor(dim.name)}-500 rounded-full" style="width: ${(dim.v1 / 25) * 100}%"></div>
      </div>

      <div class="flex items-center justify-between">
        <span class="text-gray-500">当前版本</span>
        <span class="font-bold">${dim.v2}</span>
      </div>

      <div class="mt-2 text-sm ${dim.diff >= 0 ? 'text-green-600' : 'text-red-600'}">
        <i class="fas ${dim.diff >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'} mr-1"></i>
        ${dim.analysis || '暂无分析建议'}
      </div>
    </div>
  `).join('');
}

// 获取维度对应颜色
function getDimensionColor(dimension) {
  const colors = {
    '词汇': 'blue',
    '句子': 'purple',
    '结构': 'yellow',
    '内容': 'green'
  };
  return colors[dimension] || 'blue';
}

// 渲染雷达图
function renderRadarChart(data) {
  const canvas = document.getElementById('radar-chart');
  if (!canvas) return;

  // 如果已有图表实例则先销毁
  if (canvas.chart) {
    canvas.chart.destroy();
  }

  const ctx = canvas.getContext('2d');
  canvas.chart = new Chart(ctx, {
    type: 'radar',
    data: {
      labels: data.labels,
      datasets: [
        {
          label: '前一版本',
          data: data.v1Data,
           backgroundColor: 'rgba(156, 163, 175, 0.2)',
          borderColor: '#9ca3af',
          pointBackgroundColor: '#9ca3af',

          pointRadius: 4
        },
        {
          label: '当前版本',
          data: data.v2Data,
           backgroundColor: 'rgba(59, 130, 246, 0.2)',
          borderColor: '#3b82f6',
          pointBackgroundColor: '#3b82f6',
          pointRadius: 4
        }
      ]
    },
    options: {
      responsive: true,
      scales: {
        r: {
          angleLines: { display: true },
          suggestedMin: 0,
          suggestedMax: 25,
          ticks: { stepSize: 5 }
        }
      },
      plugins: {
        legend: {
          position: 'bottom'
        }
      }
    }
  });
}

// 渲染改进建议
function renderImprovementSuggestions(suggestions) {
  const container = document.getElementById('improvement-suggestions');
  if (!container) return;

  container.innerHTML = suggestions.map((text, index) => {
    const isCritical = index === 0 || text.includes('下降') || text.includes('降低');
    return `
      <div class="flex items-start ${isCritical ? 'bg-red-50' : 'bg-blue-50'} p-3 rounded-lg">
        <div class="text-${isCritical ? 'red' : 'blue'}-500 mr-3 mt-1">
          <i class="fas ${isCritical ? 'fa-exclamation-circle' : 'fa-check-circle'}"></i>
        </div>
        <div>
          <p class="font-medium text-${isCritical ? 'red' : 'blue'}-800">${isCritical ? '需改进' : '表现良好'}</p>
          <p class="text-sm text-gray-600 mt-1">${text}</p>
        </div>
      </div>
    `;
  }).join('');
}

// 显示错误弹窗
function showErrorModal(modal, error) {
  const errorContent = `
    <div class="text-center py-10">
      <i class="fas fa-exclamation-triangle text-red-500 text-4xl mb-3"></i>
      <p class="text-lg font-medium mb-2">数据加载失败</p>
      <p class="text-gray-600 mb-4">${error.message || '未知错误'}</p>
      <button onclick="location.reload()" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors">
        重新加载
      </button>
    </div>
  `;

  const contentArea = modal.querySelector('.modal-content') || modal.querySelector('.modal-body');
  if (contentArea) {
    contentArea.innerHTML = errorContent;
  }
}

// 带版本选择的对比调用
// * 获取作文对比分析数据
// * @param {string} essayId - 作文ID
// * @param {string} versionId1 - 第一个版本ID
// * @param {string} versionId2 - 第二个版本ID
// * @param {string} token - 用户认证token
// * @returns {Promise} 包含对比分析数据的Promise
// */

async function fetchEssayComparison(essayId, currentVersionId, token) {
  try {
  // 转换版本号
    const currentVersion = String(Number(currentVersionId));
    const previousVersion = String(Math.max(0, currentVersion - 1));
    console.log(currentVersion,typeof(currentVersion),essayId);
// 参数验证
    if (!essayId || !currentVersion || !token) {
      throw new Error('缺少必要参数: essayId, version1, version2');
    }

    const params = new URLSearchParams({
      essay_id: essayId,
      version_id_2: currentVersion, // 当前版本
      version_id_1:previousVersion, // 上一个版本

    });


    // 调试日志
    console.log('请求参数:',params );
//console.log(params);

    const response = await fetch(`http://127.0.0.1:5004/analysis/compare?${params}`, {
      method: 'GET',
      headers: {
     'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    console.log('对比分析数据:', result);
if (result.code === 200) {
      return result.data;
    } else {
      throw new Error(result.message || '获取对比分析失败');
    }
  } catch (error) {
    console.error('获取对比分析出错:', error);
    throw error;
  }
}


///
// * 获取用户进步分析数据
// * @param {string} token - 用户认证token
// * @returns {Promise} 包含进步分析数据的Promise
// */
async function fetchUserProgress(token) {
  try {
    const response = await fetch('http://127.0.0.1:5004/analysis/progress', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    console.log('进步分析数据:', result);
if (result.code === 200) {
      return result.data;
    } else {
      throw new Error(result.message || '获取进步分析失败');
    }
  } catch (error) {
    console.error('获取进步分析出错:', error);
    throw error;
  }
}
